package com.webflux.demo.controller;

import com.webflux.demo.bean.User;
import com.webflux.demo.config.UserValidator;
import com.webflux.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.DataBinder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author H
 * @date 2023/1/15
 */
@RestController
@RequestMapping("/webFlux")
public class WebFluxController {

    @Autowired
    private UserService userService;

    @GetMapping("getUserById/{id}")
    public Mono<User> getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @GetMapping("getUserByUserName")
    public Flux<User> getUserByUserName(String username) {
        return userService.getUserByUserName(username);
    }

    /**
     * 定义了String -> User的类型转换器，会自动将字符串类型转换为User类型
     * @param user
     * @return
     */
    @PostMapping("user2/{user}")
    public Mono<User> insertUser2(@PathVariable User user) {
        return userService.insertUser(user);
    }

    @PostMapping("user3")
    public Mono<User> insertUser3(@Validated @RequestBody User user) {
        return userService.insertUser(user);
    }

    /**
     * 加入局部验证器，这样UserValidator就只对当前的控制器有效，而不是全局有效
     * @param dataBinder
     */
    @InitBinder
    public void initBinder(DataBinder dataBinder) {
        dataBinder.setValidator(new UserValidator());
    }

}
